package com.calvin.study.controller;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.calvin.study.entity.User;
import com.calvin.study.utils.JwtUtil;

@Controller
public class SsoServerController {

	@Autowired
	RedisTemplate<String, String> redisTemplate;

	@RequestMapping("/preLogin")
	public String preLogin(String url, HttpServletRequest request, Model model) {
		System.out.println(url);
		// 判断有没有全局的jsessionid
		HttpSession session = request.getSession(false);
		if (session == null) {
			// 表示没有其他子系统来创建过，我是第一次来
			model.addAttribute("url", url);
			// 给用户返回一个登录界面
			return "login";
		} else {
			// 有其他子系统已经创建过全局的session对象，怎么办？ TODO:
			// 直接颁发token给对应的子系统
			String token = (String) session.getAttribute("token");
			return "redirect:" + url + "?token=" + token;
		}
	}

	// 处理用户的登录请求的接口
	@RequestMapping("/login")
	public String login(String username, String password, String url, HttpServletRequest request) {
		String token = (String) request.getSession().getAttribute("token");;
	
		if(StringUtils.isNotBlank(token)) {
			return "redirect:" + url + "?token=" + token;
		}
		
		// 判断用户名和密码是否正确
		if ("Calvin".equals(username) && "123qwe".equals(password)) {
			
			// token要求，要安全性比较高，与此同时既能生成又能验证 JWT:Json Web Token
			try {
				token = JwtUtil.createJwt();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			System.out.println(token);
			// 为该用户在sso服务中添加标记，标识登录成功
			request.getSession().setAttribute("token", token);

			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			redisTemplate.opsForValue().set(token, JSON.toJSONString(user), 30, TimeUnit.MINUTES);

			// 颁发token给对应的子系统
			return "redirect:" + url + "?token=" + token;
		} else {
			return "login";
		}
	}

	@RequestMapping("/checkToken")
	public @ResponseBody User checkToken(@RequestParam(required = false) String token) {
		String cacheToken = redisTemplate.opsForValue().get(token);
		User user = null;
		if (StringUtils.isNotBlank(cacheToken) && JwtUtil.verifyJwt(token)) {
			user = JSON.parseObject(cacheToken, User.class);
		}
		return user;
	}

}
